// API服务文件 - 封装所有后端请求

// 基础URL配置
const BASE_URL = ''; // 使用相对路径，通过Vite代理处理跨域

// 请求拦截器 - 处理通用设置
async function request(url, options = {}) {
  // 设置默认headers
  const headers = {
    'Content-Type': 'application/json',
    ...options.headers
  };
  
  // 如果有token，添加到请求头
  const token = localStorage.getItem('token');
  if (token) {
    headers['Authorization'] = `Bearer ${token}`;
  }
  
  try {
    const response = await fetch(`${BASE_URL}${url}`, {
      ...options,
      headers
    });
    
    // 检查响应状态
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `请求失败: ${response.status}`);
    }
    
    // 处理响应数据
    const data = await response.json();
    
    // 检查响应结构，确保返回data字段
    if (data && data.code === 1) {
      return data.data;
    } else {
      throw new Error(data.msg || '请求失败');
    }
  } catch (error) {
    console.error('API请求错误:', error);
    throw error;
  }
}

// 用户相关API
export const userAPI = {
  // 用户登录
  login: async (username, password) => {
    return await request('/user/user/login', {
      method: 'POST',
      body: JSON.stringify({ username, password })
    });
  },
  
  // 用户注册
  register: async (userData) => {
    return await request('/user/user/register', {
      method: 'POST',
      body: JSON.stringify(userData)
    });
  },
  
  // 获取用户信息
  getUserInfo: async (userId) => {
    return await request(`/users/${userId}`, {
      method: 'GET'
    });
  },
  
  // 退出登录
  logout: async () => {
    // 模拟退出登录，因为JSON-Server可能不支持
    return await Promise.resolve({ success: true });
  }
};

// 购物车相关API
export const cartAPI = {
  // 获取购物车列表
  getCart: async (userId) => {
    return await request(`/carts?userId=${userId}`, {
      method: 'GET'
    });
  },
  
  // 添加商品到购物车
  addToCart: async (cartData) => {
    return await request('/carts', {
      method: 'POST',
      body: JSON.stringify(cartData)
    });
  },
  
  // 更新购物车商品数量
  updateQuantity: async (cartItemId, quantity) => {
    return await request(`/carts/${cartItemId}`, {
      method: 'PATCH',
      body: JSON.stringify({ quantity })
    });
  },
  
  // 删除购物车商品
  removeFromCart: async (cartItemId) => {
    return await request(`/carts/${cartItemId}`, {
      method: 'DELETE'
    });
  }
};

// 商品相关API
export const productAPI = {
  // 获取商品列表
  getProducts: async (params = {}) => {
    // 构建查询字符串
    const queryString = Object.entries(params)
      .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
      .join('&');
    
    const url = queryString ? `/products?${queryString}` : '/products';
    return await request(url, {
      method: 'GET'
    });
  },
  
  // 获取商品详情
  getProductDetail: async (productId) => {
    return await request(`/products/${productId}`, {
      method: 'GET'
    });
  },
  
  // 获取商品分类
  getCategories: async () => {
    return await request('/categories', {
      method: 'GET'
    });
  }
};

// 订单相关API
export const orderAPI = {
  // 创建订单
  createOrder: async (orderData) => {
    return await request('/orders', {
      method: 'POST',
      body: JSON.stringify(orderData)
    });
  },
  
  // 获取订单列表
  getOrders: async (userId) => {
    return await request(`/orders?userId=${userId}`, {
      method: 'GET'
    });
  },
  
  // 获取订单详情
  getOrderDetail: async (orderId) => {
    return await request(`/orders/${orderId}`, {
      method: 'GET'
    });
  },
  
  // 取消订单
  cancelOrder: async (orderId) => {
    return await request(`/orders/${orderId}`, {
      method: 'PATCH',
      body: JSON.stringify({ status: 'cancelled' })
    });
  }
};

export default {
  userAPI,
  cartAPI,
  productAPI,
  orderAPI
};